package com.zhongshengnetwork.rightbe.wzt.view;

import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
//import android.support.annotation.NonNull;
//import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.wang.avi.AVLoadingIndicatorView;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.Constant.Constant;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.BaseAnalyticsFragment;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.activity.ReportActivity;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.common.customview.KeyMapDailog;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.DryCommentModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.lang.activity.LangCommentActivity;
import com.zhongshengnetwork.rightbe.lang.activity.UserLangActivity;
import com.zhongshengnetwork.rightbe.login.LoginActivity;
import com.zhongshengnetwork.rightbe.view.controller.CommonItemViewController;
import com.zhongshengnetwork.rightbe.wzt.activity.WZTContentActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.content.Context.CLIPBOARD_SERVICE;

public class WZTCommentFragment extends BaseAnalyticsFragment {

    private long id;
    private int pageindex = 0;
    private static final int Records = 20;
    private boolean isHasMore = false;
    private List<DryCommentModel> list;
    private RecyclerView listview;
    private WZTCommentRecyclerAdapter adapter;
    private View rootView;//缓存Fragment view
    private String userid = "";//作者

    //加载动画
    private AVLoadingIndicatorView avi;
    private RefreshLayout mRefreshLayout;

    private List<String> moreList;
    private int opIndex = 0;
    private int shareType = 0;
    private boolean isShareWx = false;
    private ClipboardManager myClipboard;

    private LinearLayout lang_detail_common_button;
    //评论弹出框
    private KeyMapDailog dialog = null;
    //private NestedScrollView wzt_nestedScrollView_layout;

    private MyCommentListener myListener;//②作为属性定义
    //①定义回调接口
    public interface MyCommentListener{
        public void commentSend();
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        myListener = (MyCommentListener) getActivity();
    }

    public static WZTCommentFragment newInstance(long id, String userid){
        WZTCommentFragment wztCommentFragment = new WZTCommentFragment();
        Bundle bundle = new Bundle();
        bundle.putLong("id",id);
        bundle.putString("userid", userid);
        wztCommentFragment.setArguments(bundle);
        return wztCommentFragment;
    }

    public void addComment(DryCommentModel dryCommentModel){
        if (dryCommentModel != null){
            list.add(0, dryCommentModel);
            //adapter.notifyDataSetChanged();
            //adapter.notifyItemInserted(0);
            adapter.notifyDataSetChanged();
            //listview.setSelection(0);
        }
    }

    private void onClickCopy(String text){
        try{
            ClipData myClip = ClipData.newPlainText("text", text);
            myClipboard.setPrimaryClip(myClip);
            Toast.makeText(getActivity(), "内容已复制~",
                    Toast.LENGTH_SHORT).show();
        }catch (Exception e){

        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle args = getArguments();
        if (args != null){
            id = args.getLong("id");
            userid = args.getString("userid");
        }
        myClipboard = (ClipboardManager)getActivity().getSystemService(CLIPBOARD_SERVICE);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {

            rootView = inflater.inflate(R.layout.wzt_viewpaper_comment_layout, container, false);
            avi = (AVLoadingIndicatorView)rootView.findViewById(R.id.avi);
            pageindex = 0;
            if (list == null){
                list = new ArrayList<DryCommentModel>();
            }

            listview=(RecyclerView) rootView.findViewById(R.id.wzt_listview);

            //LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
            LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false) {
                @Override
                public boolean canScrollVertically() {
                    return false;
                }
            };
            listview.setLayoutManager(layoutManager);
            listview.setHasFixedSize(false);
            listview.setNestedScrollingEnabled(false);
            ((DefaultItemAnimator) listview.getItemAnimator()).setSupportsChangeAnimations(false);//解决局部更新闪烁问题
            adapter = new WZTCommentRecyclerAdapter(getActivity(), list, id, userid);
            listview.setAdapter(adapter);

            lang_detail_common_button = (LinearLayout)rootView.findViewById(R.id.lang_detail_common_button);
            lang_detail_common_button.setClickable(true);
            lang_detail_common_button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    myListener.commentSend();
                }
            });

            mRefreshLayout = rootView.findViewById(R.id.refreshLayout);
            //设置 Header 为 贝塞尔雷达 样式
            mRefreshLayout.setRefreshHeader(new BezierRadarHeader(getActivity()).setEnableHorizontalDrag(true));//BezierRadarHeader
            //设置 Footer 为 球脉冲 样式
            mRefreshLayout.setRefreshFooter(new ClassicsFooter(getActivity()).setSpinnerStyle(SpinnerStyle.FixedBehind));//BallPulseFooter ClassicsFooter
            mRefreshLayout.setPrimaryColors(AppThemeUtils.getInstance().getRefreshBackgroundColor(),AppThemeUtils.getInstance().getRefreshAccessColor());
            mRefreshLayout.setEnableRefresh(false);//禁用刷新
            mRefreshLayout.setEnableLoadMore(false);//启用加载
            mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
                @Override
                public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                    getData();
                }
            });

            LinearLayout comment_layout = (LinearLayout) rootView.findViewById(R.id.comment_layout);
            comment_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            LinearLayout lang_detail_common_button = (LinearLayout) rootView.findViewById(R.id.lang_detail_common_button);
            lang_detail_common_button.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
            listview.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());

            getData();
        }else {
            //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
        }

        return rootView;
    }

    private void getData(){

        new Thread(new Runnable() {
            @Override
            public void run() {
                final Map<String,String> map = new HashMap<String, String>();
                map.put("pageIndex",pageindex+"");
                map.put("pageRecord",Records+"");
                map.put("dataId",id+"");
                if (CommonUtils.isLogin() == true){
                    map.put("token", CustomApplication.loginModel.getToken());
                }
                String url = "weishu/theme/comment/list.do";
                HttpsUtils.miniAppDo(map, url,  new HttpCallBack() {
                    @Override
                    public void onSuccess(String data) {

                        if (getActivity() != null){
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mRefreshLayout.finishLoadMore();
                                    CommonModel commonModel = GsonTools.getCommonModel(data);
                                    if (commonModel.getFlag().equals("1")){
                                        List<DryCommentModel> l = GsonTools.getDryCommentModel1(data);
                                        int fromposition = list.size();
                                        if (l != null && l.size() > 0){
                                            if (l.size() >= Records){
                                                mRefreshLayout.setEnableLoadMore(true);
                                            }else {
                                                mRefreshLayout.setEnableLoadMore(false);
                                            }
                                            if (pageindex == 0){
                                                list.clear();
                                            }
                                            list.addAll(l);
                                            pageindex += 1;
                                        }else {
                                            if (pageindex > 0) {
                                                ToastUtil.show(getActivity(), "亲，我是有底线的~");
                                            }
                                            mRefreshLayout.setEnableLoadMore(false);
                                        }
                                        if (pageindex == 0){
                                            adapter.notifyDataSetChanged();
                                        }else {
                                            adapter.notifyItemRangeChanged(fromposition, l.size());
                                        }
                                    }else {
                                        CustomApplication.showTip(commonModel, getActivity());
                                    }
                                }
                            });
                        }

                    }

                    @Override
                    public void onError(String msg) {
                        if (getActivity() != null){
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mRefreshLayout.finishLoadMore();
                                }
                            });
                        }
                    }
                });
            }
        }).start();

    }

}
